<template>
	<view class="courseDetail">
		<u-navbar title="课程学习" :autoBack="true" :placeholder="true">
		</u-navbar>

		<view v-if="courseDetail.chapterType =='1'" class="videoContent">
			<video :src="courseDetail.address" :initial-time="videoEcho.viewedDuration" controls
				@loadedmetadata="onVideoLoaded" @pause="handlePause" @timeupdate="onTimeUpdate"></video>
		</view>

		<view v-if="courseDetail.chapterType =='2'" class="videoContent imgContent">
			<view class="NumberContent">
				{{courseCurrindex+1}}/{{courseDetail.address.length}}
			</view>
			<view class="pointsImgBox">
				<image class="leftIcon" src="https://mp.blrwworkshop.com/imgs/lefts.png" mode=""
					@click="courseCurrindex = courseCurrindex > 0 ? courseCurrindex - 1 : courseDetail.address.length - 1">
				</image>
				<image class="rightIcon" src="https://mp.blrwworkshop.com/imgs/rights.png" mode=""
					@click="courseCurrindex = courseCurrindex < courseDetail.address.length - 1 ? courseCurrindex + 1 : 0">
				</image>
			</view>
			<swiper class="swiper" circular :autoplay="false" :interval="interval" :duration="duration"
				:current="courseCurrindex" @change="changecourseImngList">
				<swiper-item v-for="(item,index) in courseDetail.address" :key="index">
					<image :src="item" mode=""></image>
				</swiper-item>
			</swiper>
		</view>


		<view class="tabsContent">
			<view class="tabsItem" v-for="(item,index) in tabsList" :key="index" @click="handleChnangeTabs(item,index)">
				<view class="">
					{{item.name}}
				</view>
				<view v-if="tabsCurrindex==index" class="line" :class="{bg_student:role ==1,bg_parent:role==2}"></view>
			</view>
		</view>

		<view class="fgxContent">
			<image src="https://mp.blrwworkshop.com/imgs/fgx.png" mode=""></image>
		</view>


		<scroll-view scroll-y="true" class="scroll-Y">

			<view v-if="tabsCurrindex==0" class="detail">
				<view class="detail_title">
					{{courseDetail.lessonName || ""}}
				</view>
				<view class="detail_cnotent">
					<u-parse :content="courseDetail.chapterIntro"></u-parse>
				</view>
			</view>


			<view v-if="tabsCurrindex ==1" class="Directory">
				<view class="Directory_title">
					{{courseDetail.gradeName || ""}}{{courseDetail.volumeType==1?'上册':'下册'}}第{{courseDetail.unitName || ""}}
				</view>
				<view class="Tag_Box">
					<view class="Tag_Box_Item" v-for="(item,index) in TagList"
						:class="{Tag_Box_Itemed:TagCurrindex==index && role ==1,bg_parent:TagCurrindex==index && role ==2}"
						:key="index" @click="handleChangeTag(item,index)">
						{{item.labelName || ""}}
					</view>
				</view>

				<view v-if="DirectoryList.length>0" class="DirectoryList">
					<view class="DirectoryLItem" v-for="(item,index) in DirectoryList" :key="index"
						@click="handleChangeCourse(item,index)">
						<view class="playerBox">
							<image v-if="item.chapterId == chapterId"
								:src="role==1 ? 'https://mp.blrwworkshop.com/imgs/player.png' :'https://mp.blrwworkshop.com/imgs/players.png' "
								mode="">
							</image>
							<image v-else
								:src="role==1 ? 'https://mp.blrwworkshop.com/imgs/stop.png' : 'https://mp.blrwworkshop.com/imgs/stops.png'"
								mode="">
							</image>
						</view>
						<view class="DirectoryLItem_content">
							<view class="name">
								{{item.chapterName || ""}}
							</view>
							<view class="Directory_type" :class="{bg_student:role ==1,bg_parent:role ==2}">
								{{item.chapterType==1?"视频":"图文"}}
							</view>
						</view>
						<view class="status">
							<image v-if="item.progress ==100" src="https://mp.blrwworkshop.com/imgs/ykw.png" mode="">
							</image>
							<image v-if="item.isLatestWatched ==1 && item.chapterId != chapterId"
								:src="role==1 ? 'https://mp.blrwworkshop.com/imgs/lastimg.png' :'https://mp.blrwworkshop.com/imgs/lastimgs.png' "
								mode="">
							</image>
							<image v-if="item.chapterId == chapterId"
								:src="role==1 ?'https://mp.blrwworkshop.com/imgs/studying.png' : 'https://mp.blrwworkshop.com/imgs/studyings.png'"
								mode="">
							</image>
						</view>
					</view>
				</view>

				<view v-else class="dataNull">
					<image
						:src="role ==1 ?'https://mp.blrwworkshop.com/imgs/dataNull.png' :'https://mp.blrwworkshop.com/imgs/dataNulls.png'"
						mode="">
					</image>
					<view class="">
						暂无目录
					</view>
				</view>

			</view>



			<view v-if="tabsCurrindex ==2" class="KnowledgePoints">

				<view v-if="PointList.length>0" class="">

					<view v-if="!points" class="fileList">
						<view class="fileItme" v-for="(item,index) in PointList" :key="index"
							@click="handlepointsDtail(item,index)">
							<view v-if="editFlag" class="checkBox">
								<image src="https://mp.blrwworkshop.com/imgs/checks.png" mode=""></image>
							</view>
							<image src="https://mp.blrwworkshop.com/imgs/pdfIcon.png" mode=""></image>
							<view class="fileName">
								{{item.name || ""}}
							</view>
							<view class="lookBtn" :class="role==1?'bg_student':'bg_parent'">
								查看
							</view>
						</view>
					</view>

					<view v-else class="tabsContents">
						<u-tabs :list="PointListAll" :lineColor="role==1?'#FFA116':'#41C76F'" :inactiveStyle="{
				    color: '#B4B4B4',
				}" @click="clickPointTabs"></u-tabs>
					</view>

					<view v-if="points" class="pointImngContent">
						<view v-if="pointsImgList.length>0" class="">
							<view class="NumberBox">
								{{Pointcurrent+1 || ""}}/{{pointsImgList.length}}
							</view>
							<swiper v-if="points" class="pointImngList" circular :autoplay="false" :interval="interval"
								:duration="duration" :current="Pointcurrent" @change="changePointImngList">
								<swiper-item class="pointItem" v-for="(item,index) in pointsImgList" :key="index">
									<image class="pointImg" :src="item.address" mode="widthFix"></image>
								</swiper-item>
							</swiper>
						</view>
						<view v-else class="dataNull">
							<image
								:src="role ==1 ?'https://mp.blrwworkshop.com/imgs/dataNull.png' :'https://mp.blrwworkshop.com/imgs/dataNulls.png'"
								mode="">
							</image>
							<view class="">
								暂无知识点内容~
							</view>
						</view>
					</view>
				</view>

				<view v-else class="dataNull">
					<image
						:src="role ==1 ?'https://mp.blrwworkshop.com/imgs/dataNull.png' :'https://mp.blrwworkshop.com/imgs/dataNulls.png'"
						mode=""></image>
					<view class="">
						暂无知识点
					</view>
				</view>


			</view>
		</scroll-view>

	</view>
</template>
<script>
	import {
		viewChapter,
		qryLabel,
		qryCatalogue,
		qryKnowledgePointByChapter,
		qryKnowledgePointByChapterAll,
		viewKnowledgePointImg,
		saveWatchRecord
	} from "@/api/course.js"
	export default {
		data() {
			return {
				role: uni.getStorageSync('role'),
				tabsList: [{
						id: 1,
						name: "详情"
					},
					{
						id: 2,
						name: "目录"
					},
					{
						id: 3,
						name: "知识点"
					},
				],
				tabsCurrindex: 0,
				TagList: [],
				labelId: "",
				TagCurrindex: 0,
				DirectoryList: [],
				PointList: [], //tabs知识点
				PointListAll: [], //tabs知识点不分页
				points: false,
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				courseCurrindex: 0, //课程图片
				chapterId: null,
				courseDetail: {},
				CatalogueNum: 1,
				PointpageNum: 1,
				PointId: "", //知识点id
				pointsImgList: [], //知识点图片列表
				autoplay: true,
				interval: 2000,
				duration: 500,
				Pointcurrent: 0, //知识点图片index
				totalDuration: null, //总时长
				currentDuration: null, //当前时长
				videoEcho: {
					progress: null,
					viewedDuration: null,
					viewedDurationWeb: null,
				},
				jumpChapterId: null,

			}
		},
		async onLoad(options) {
			this.chapterId = options.chapterId
			this.handleGetviewChapter()
			await this.handleGetqryLabel()
			await this.handleGetqryCatalogue()
			this.handleqryKnowledgePointByChapter()
			this.handleGetqryKnowledgePointByChapterAll()
		},
		onUnload() {
			// console.log("onUnload")
			this.handlePause()
		},
		methods: {
			// 详情
			async handleGetviewChapter() {
				let res = await viewChapter({
					chapterId: this.chapterId
				})
				if (res.code == 200) {
					this.courseDetail = res.data
					if (this.courseDetail.chapterType == 1) {
						this.videoEcho.progress = res.progress
						this.videoEcho.viewedDuration = res.viewedDuration
						this.videoEcho.viewedDurationWeb = res.viewedDurationWeb
						this.currentDuration = res.viewedDuration;
					}
					if (this.courseDetail.chapterType == 2) {
						this.courseDetail.address = this.courseDetail.address.split(",")
					}
				}
			},
			//标签
			async handleGetqryLabel() {
				let res = await qryLabel()
				if (res.code == 200) {
					this.TagList = res.data || []
					this.labelId = this.TagList[0].id
				}
			},
			//目录
			async handleGetqryCatalogue() {
				let res = await qryCatalogue({
					chapterId: this.chapterId,
					labelId: this.labelId,
					pageSize: 10,
					pageNum: this.CatalogueNum
				})
				if (res.code == 200) {
					this.DirectoryList = [...this.DirectoryList, ...res.rows]
				}
			},
			//知识点
			async handleqryKnowledgePointByChapter() {
				let res = await qryKnowledgePointByChapter({
					chapterId: this.chapterId,
					pageSize: 10,
					pageNum: this.PointpageNum

				})
				this.PointList = [...this.PointList, ...res.rows]
			},
			//知识点-不分页
			async handleGetqryKnowledgePointByChapterAll() {
				let res = await qryKnowledgePointByChapterAll({
					chapterId: this.chapterId,
				})
				this.PointListAll = [...this.PointListAll, ...res.data]
			},
			handleChnangeTabs(item, index) {
				this.tabsCurrindex = index
				this.points = false
			},
			handleChangeTag(item, index) {
				this.TagCurrindex = index
				this.labelId = item.id
				this.CatalogueNum = 1
				this.DirectoryList = []
				this.handleGetqryCatalogue()
			},
			changecourseImngList(event) {
				this.courseCurrindex = event.detail.current
			},
			handlepointsDtail(item, index) {
				this.points = true
				this.PointId = item.id
				this.handleGetPointDetail()
			},
			async handleGetPointDetail() {
				let res = await viewKnowledgePointImg({
					id: this.PointId
				})
				this.pointsImgList = res.data
			},
			changePointImngList(event) {
				this.Pointcurrent = event.detail.current
			},
			clickPointTabs(item) {
				// console.log("item", item)
				this.PointId = item.id
				this.handleGetPointDetail()
			},

			async handleChangeCourse(item, index) {
				await this.handlePause()
				this.chapterId = item.chapterId
				this.DirectoryList = []
				this.PointList = []
				this.PointListAll = []
				await this.handleGetviewChapter()
				await this.handleGetqryLabel()
				await this.handleGetqryCatalogue()
				await this.handleqryKnowledgePointByChapter()
				await this.handleGetqryKnowledgePointByChapterAll()
			},

			// 视频元数据加载完成时触发
			onVideoLoaded(e) {
				this.totalDuration = e.detail.duration;
			},

			// 实时更新播放时间（可选，用于实时显示进度）
			onTimeUpdate(e) {
				this.currentDuration = e.detail.currentTime;
				// console.log("实时更新", e.detail.currentTime)
			},
			//保存记录
			async handlePause() {
				if (this.role == 2) return
				let data = {}
				if (this.courseDetail.chapterType == 1) {
					if (this.currentDuration == 0) return
					data = {
						chapterId: this.chapterId,
						lastTime: this.getCurrentDateTime().datetime,
						viewedDuration: this.currentDuration,
						progress: Math.ceil(Number(this
							.currentDuration) / Number(this.totalDuration) * 100),
						viewedDurationWeb: this.formatSeconds(this.currentDuration)
					}
				}
				if (this.courseDetail.chapterType == 2) {
					data = {
						chapterId: this.chapterId,
						lastTime: this.getCurrentDateTime().datetime,
						progress: (Number(this
							.courseCurrindex + 1) / Number(this.courseDetail.address.length)) * 100,
					}
				}
				let res = await saveWatchRecord(data)
				if (res.code == 200) {
					uni.$emit('CourseListUpdated', {
						refresh: true
					});
				}
			},
			// 格式化时长为 时:分:秒
			formatDuration(seconds) {
				if (!seconds) return '00:00';
				const h = Math.floor(seconds / 3600);
				const m = Math.floor((seconds % 3600) / 60);
				const s = Math.floor(seconds % 60);
				return `${h > 0 ? (h < 10 ? '0' + h : h) + ':' : ''}${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`;
			},
			//当前时间
			getCurrentDateTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = now.getMonth() + 1;
				const day = now.getDate();
				const hour = now.getHours();
				const minute = now.getMinutes();
				const second = now.getSeconds();

				// 补零处理
				const format = (n) => n.toString().padStart(2, '0');

				return {
					year,
					month,
					day,
					hour,
					minute,
					second,
					// 完整字符串格式
					datetime: `${year}-${format(month)}-${format(day)} ${format(hour)}:${format(minute)}:${format(second)}`
				};
			},
			//计算时长 时分秒
			formatSeconds(seconds) {
				// 处理无效值
				if (typeof seconds !== 'number' || seconds < 0 || isNaN(seconds)) {
					return '0分0秒';
				}

				// 计算时、分、秒
				const hours = Math.floor(seconds / 3600); // 小时
				const minutes = Math.floor((seconds % 3600) / 60); // 分钟
				const secs = Math.floor(seconds % 60); // 秒

				// 拼接结果（根据是否有小时决定格式）
				let result = '';
				if (hours > 0) {
					result += `${hours}小时`;
				}
				result += `${minutes}分${secs}秒`;
				return result;
			}
		}
	}
</script>

<style scoped lang="scss">
	.courseDetail {
		width: 100%;
		min-height: 100vh;
		background: #F9F9F9;

		.videoContent {
			width: 100%;
			height: 428rpx;
			// background: #FFEED4;
			position: fixed;
			top: 160rpx;

			video {
				width: 100%;
				height: 428rpx;
			}
		}

		.imgContent {
			width: 100%;
			padding-top: 30rpx;
			padding: 20rpx;
			box-sizing: border-box;

			.NumberContent {
				width: 94rpx;
				height: 36rpx;
				background: #000000;
				border-radius: 6rpx;
				opacity: 0.18;
				font-weight: 500;
				font-size: 24rpx;
				color: #FFFFFF;
				text-align: center;
				position: absolute;
				top: 20rpx;
				left: 30rpx;
				z-index: 999;

			}

			.pointsImgBox {
				image {
					width: 56rpx;
					height: 56rpx;
					position: absolute;
					z-index: 999;
					top: 180rpx;
				}

				.leftIcon {
					left: 10rpx;
				}

				.rightIcon {
					right: 10rpx;
				}
			}



			.swiper {
				width: 690rpx;
				height: 386rpx;
				margin: auto;

				image {
					width: 690rpx;
					height: 386rpx;
					// border-radius: 20rpx;
				}
			}
		}

		.tabsContent {
			width: 100%;
			height: 70rpx;
			display: flex;
			position: fixed;
			top: 588rpx;
			background-color: #ffffff;
			// background-color: pink;

			.tabsItem {
				width: 33.33%;
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-top: 16rpx;

				.line {
					width: 30rpx;
					height: 10rpx;
					background-color: #FFA116;
					margin-top: 14rpx;
				}
			}
		}

		.fgxContent {
			width: 100%;
			position: fixed;
			top: 640rpx;

			image {
				width: 100%;
				height: 4rpx;
			}

		}

		.dataNull {
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 200rpx;
			font-weight: 400;
			font-size: 28rpx;
			color: #DDDDDD;
			margin-top: 20rpx;

			image {
				width: 330rpx;
				height: 330rpx;

			}
		}

		.scroll-Y {
			position: fixed;
			top: 662rpx;
			width: 100%;
			height: calc(100vh - 660rpx);
			padding-bottom: 70rpx;

			.detail {
				width: 100%;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				background-color: #ffffff;

				.detail_title {
					font-weight: 600;
					font-size: 36rpx;
					color: #333333;
				}

				.detail_cnotent {
					margin-top: 28rpx;
				}
			}

			.Directory {
				width: 100%;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				background-color: #ffffff;

				.Directory_title {
					font-weight: 600;
					font-size: 32rpx;
					color: #333333;
				}

				.Tag_Box {
					width: 100%;
					height: 84rpx;
					// background: #FFFFFF;
					// box-shadow: 0rpx 6rpx 14rpx 0rpx rgba(180, 180, 180, 0.11);
					padding: 20rpx 24rpx;
					box-sizing: border-box;
					display: flex;
					align-items: center;

					.Tag_Box_Item {
						width: 138rpx;
						height: 44rpx;
						background: #EAEAEA;
						border-radius: 22rpx;
						font-weight: 500;
						font-size: 24rpx;
						color: #C7C7C7;
						line-height: 44rpx;
						text-align: center;
						margin-right: 12rpx;
					}

					.Tag_Box_Itemed {
						background-color: #FFA116;
						color: #ffffff;
					}
				}

				.DirectoryList {
					width: 100%;


					.DirectoryLItem {
						width: 100%;
						padding: 34rpx 0;
						box-sizing: border-box;
						display: flex;
						align-items: center;
						margin-top: 2rpx;
						border-top: 1rpx solid #F9F9F9;
						position: relative;

						.playerBox {
							image {
								width: 54rpx;
								height: 54rpx;
							}
						}

						.DirectoryLItem_content {
							width: 496rpx;
							margin-left: 12rpx;

							.name {
								width: 496rpx;
								font-weight: 550;
								font-size: 28rpx;
								color: #333333;
								overflow: hidden;
								/* 隐藏溢出内容 */
								text-overflow: ellipsis;
								/* 显示省略号 */
								white-space: nowrap;
								/* 禁止换行 */
							}

							.Directory_type {
								width: 76rpx;
								height: 36rpx;
								border-radius: 6rpx;
								font-weight: 400;
								font-size: 24rpx;
								color: #FFFFFF;
								line-height: 36rpx;
								text-align: center;
								margin-top: 12rpx;
							}

						}

						.status {

							position: absolute;
							top: 0;
							right: 0;

							image {
								width: 130rpx;
								height: 40rpx;
							}
						}
					}

				}


			}

			.KnowledgePoints {
				width: 100%;

				.fileList {
					width: 100%;
					margin-top: 1rpx;


					.fileItme {
						width: 100%;
						display: flex;
						align-items: center;
						height: 120rpx;
						background-color: #ffffff;
						padding: 24rpx 32rpx;
						box-sizing: border-box;
						margin-bottom: 1rpx;

						.checkBox {
							image {
								width: 36rpx;
								height: 36rpx;
								margin-right: 20rpx;
							}
						}

						image {
							width: 72rpx;
							height: 72rpx;
						}

						.fileName {
							font-weight: 400;
							font-size: 28rpx;
							color: #333333;
							line-height: 40rpx;
							width: 420rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							margin-left: 8rpx;
						}

						.lookBtn {
							width: 100rpx;
							height: 48rpx;
							// background: #FFA116;
							border-radius: 8rpx;
							font-weight: 400;
							font-size: 24rpx;
							color: #FFFFFF;
							line-height: 48rpx;
							text-align: center;
							margin-left: 86rpx;
						}
					}
				}

				.tabsContents {
					width: 100%;
					height: 84rpx;
					background: #FFFFFF;
				}

				.pointImngContent {
					width: 100%;
					background: #FFFFFF;
					padding: 20rpx;
					box-sizing: border-box;
					position: relative;

					.NumberBox {
						width: 104rpx;
						height: 40rpx;
						background: #000000;
						box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(255, 161, 22, 0.19);
						border-radius: 20rpx;
						opacity: 0.3;
						color: #ffffff;
						text-align: center;
						font-size: 28rpx;
						position: absolute;
						top: 40rpx;
						left: 40rpx;
						z-index: 999;

					}
				}

				.pointImngList {
					width: 100%;
					overflow: visible;
					/* 允许内容超出默认高度 */
					min-height: 1000rpx;
					/* 避免容器初始高度为0 */
				}

				.pointItem {
					width: 100%;
					height: auto;
					/* 轮播项高度随图片自适应 */
					display: flex;
					justify-content: center;
					/* 图片居中显示 */

					image {
						width: 100%;
						/* 图片宽度占满容器 */
						height: auto;
						/* 高度随比例自适应（配合 mode="widthFix"） */
						/* 可选：添加最大高度限制，防止图片过高 */
						max-height: 80vh;
						/* 例如不超过屏幕高度的80% */
					}
				}
			}



		}


	}
</style>